const fs = require('fs');
const path = require('path');
const _ = require('lodash');
const THEMES_CONFIG = require('../themes.config.ts');

const OUTPUT_DIR = 'src/styles/themes';

const write = _.partial(fs.writeFileSync, _, _, 'utf8');

/**
 * 生成 styles/themes 目录
 */
if (!fs.existsSync(OUTPUT_DIR)) {
  fs.mkdir(OUTPUT_DIR, (err) => {
    console.error(err)
  });
}

/**
 * 获取 styles/themes 文件夹下变量的 scss 文件内容
 * @param variableConfig 变量配置
 */
const getModifyVariablesContent = (variableConfig) => {
  const declaredContent = _.map(_.entries(variableConfig), ([key, value]) => `${key}: ${value};`);
  return declaredContent.join('\r');
};

/**
 * 生成 styles/themes 下变量的 scss 文件
 * @param theme: 主题配置关键字； config：主题配置信息；
 */
const createThemeVariablesFile = ([theme, config]) => {
  const fileName = `_${theme}_variable.scss`;
  const modifyVariablesContent = getModifyVariablesContent(config);
  const content = `${modifyVariablesContent}`;
  const outPutFilePath = path.join(OUTPUT_DIR, fileName);
  let flag = true;
  try {
    write(outPutFilePath, content);
  } catch (e) {
    flag = false;
  }
  return flag;
}

/**
 * 生成 styles/themes 下变量的 scss 文件
 * @param theme 主题配置关键字
 */
const createBricksStyleSetFile =  (theme) => {
  let flag = true;
  const writePathName = `src/styles/bricks_${theme}.scss`;
  try {
    /** 创建读取文件流 */
    const readable =  fs.createReadStream('src/styles/bricks.scss');
    /** 创建写入流 */
    const writable =  fs.createWriteStream(writePathName);
    /** 通过管道来传输流 */
   readable.pipe(writable);
    fs.readFile(writePathName, 'utf8', function (err, files) {
      var result = files.replace(/default_variable/g, `${theme}_variable`);
      fs.writeFile(writePathName, result, 'utf8', function (err) {
        if (err) return console.log(err);
      });
    })
  } catch (e) {
    flag = false;
  }
  return flag;
}

/**
 * 遍历生成主题变量文件、样式集合文件
 */
_.forEach(_.entries(THEMES_CONFIG), ([theme, config]) => {
  createThemeVariablesFile([theme, config]);
  createBricksStyleSetFile(theme);
});
